﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MShop.Core.DataAccess;
using MShop.Core.Domain;
using MShop.Core;
using MShop.Core.Epay.Ali;
using MShop.Core.Util;
using System.Collections.Specialized;
using MShop.Core.Service.Search;
using Lucene.Net.Analysis.PanGu;
using PanGu.HighLight;
using System.Text;
using Lucene.Net.Analysis;
using PanGu;

namespace MShop.Web.Controllers
{
    public class SearchController : ControllerBase
    { 
        private readonly ISearchService _SearchService;
        public SearchController(ISearchService searchService)
        {
            _SearchService = searchService;
        }


        public ActionResult Index(int? page, int? pageSize, string key)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                return RedirectToAction("index", "home");
            }            

            AppendMeta("搜索关键字 " + key + " 的结果");
            if (!pageSize.HasValue)
            {
                pageSize = 10;
            }
            if (!page.HasValue)
            {
                page = 1;
            }

           SearchResultCollection searchresult = new SearchResultCollection();

            string querytext = GetKeyWordsSplitBySpace(key, new PanGuTokenizer());

            if (!string.IsNullOrEmpty(querytext))
            {
                searchresult = _SearchService.FindContent(querytext, page.Value - 1, pageSize.Value);
            }

            SimpleHTMLFormatter simpleHTMLFormatter =
                      new PanGu.HighLight.SimpleHTMLFormatter("<font color=\"red\">", "</font>");

            Highlighter highlighter = new PanGu.HighLight.Highlighter(simpleHTMLFormatter, new Segment());

            highlighter.FragmentSize = 500;

            for (int i = 0; i < searchresult.Count; i++)
            {
                searchresult[i].Abstract = highlighter.GetBestFragment(key, searchresult[i].Summary);
                searchresult[i].TitleHighLighter = highlighter.GetBestFragment(key, searchresult[i].Title);
                if (string.IsNullOrEmpty(searchresult[i].TitleHighLighter))
                {
                    searchresult[i].TitleHighLighter = searchresult[i].Title;
                }
                if (string.IsNullOrEmpty(searchresult[i].Abstract))
                {
                    searchresult[i].Abstract = searchresult[i].Summary;
                }
            }



            return View(searchresult);
        }


        public List<string> SplitKeyWords(string keywords, Analyzer analyzer)
        {
            System.IO.StreamReader reader = new System.IO.StreamReader(PanGu.Framework.Stream.WriteStringToStream(keywords,
                Encoding.UTF8), Encoding.UTF8);

            TokenStream tokenStream = analyzer.TokenStream("", reader);

            global::Lucene.Net.Analysis.Token token = tokenStream.Next();

            List<string> result = new List<string>();

            while (token != null)
            {
                result.Add(keywords.Substring(token.StartOffset(), token.EndOffset() - token.StartOffset()));
                token = tokenStream.Next();
            }

            return result;

        }

        [NonAction]
        public string GetKeyWordsSplitBySpace(string keywords, PanGuTokenizer ktTokenizer)
        {
            StringBuilder result = new StringBuilder();

            ICollection<WordInfo> words = ktTokenizer.SegmentToWordInfos(keywords);

            foreach (WordInfo word in words)
            {
                if (word == null)
                {
                    continue;
                }

                result.AppendFormat("{0}^{1}.0 ", word.Word, (int)Math.Pow(3, word.Rank));
            }

            return result.ToString().Trim();
        }

    }
   
}
